package controllers;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import lib.Subject;
import models.Person;

public class PersonController
	extends ControllerAbstract 
{

	public ArrayList<Person> person_list = new ArrayList<Person>(); 
	
	public PersonController()
	{
		registerController();
		person_list = read_Person();
	}
		
	public ArrayList<Person> read_Person()
	{
		
		String filename = "person.ser"; 
		try
		{
			FileInputStream fis = new FileInputStream(filename);
			ObjectInputStream in = new ObjectInputStream(fis);	
			person_list = (ArrayList<Person>) in.readObject();
		}
		catch(Exception e)
		{
			return (new ArrayList<Person>());
		}
		
		return person_list;
	}
	
	//Write a new entry into the list
	
	public void write_Person(Person person)
	{
		String filename = "person.ser";
		
		if(!already_Exist(person, read_Person()))
		{
			person_list.add(person);
			
			
			try 
			{
				FileOutputStream fos = new FileOutputStream(filename);
				ObjectOutputStream out = new ObjectOutputStream(fos);
				out.writeObject(person_list);
				out.close();
			}
			catch(Exception e)
			{
				
			}
		}
		else
		{
			JOptionPane.showMessageDialog(null, "Sorry, a person with this employee ID already exists in the system.");
		}
		
		
		

			
		
	}
	
	//See if the employee already exists in the array. 
	
	public boolean already_Exist(Person person, ArrayList<Person> list)
	{
		try
		{
			for(int i = 0; i < list.size(); i++)
			{
				if(list.get(i).getEmployeeNumber().compareTo(person.getEmployeeNumber()) == 0)
				{
					return true;
				}
				
			}
			
			return false;
		}
		catch (Exception e)
		{
			return false;
		}
	}
	
	public void message_Person()
	{
		Person person;
		
		ArrayList<Person> list = read_Person();
		
		for(int i = 0; i < list.size(); i++)
		{
			JOptionPane.showMessageDialog(null, "Saved numbers: \n\n" + list.get(i).getEmployeeNumber());
		}
		
	}
	@Override
	public String getShortName() {
		return "PersonController";
	}

	@Override
	public void update(Subject o) {
		// TODO Auto-generated method stub
		
	}
}

